# -*- coding: utf-8 -*-
#
# Copyright (C) Mikael Schönenberg 2008
#
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
# Support classes for tests for kopsimo.py
#

import shutil
import os
import tempfile

class Fake(object):

    def __init__(self, **kw):
        self.__dict__.update(kw)

class FakeAddon(object):

    localVersion = None
    downloadVersion = None

    def __init__(self, id=None):
        self.id = id
        self.calls = []

    def fetch(self):
        self.calls.append('fetch')

    def install(self):
        self.calls.append('install')

    def save(self, targetDir):
        self.calls.append(('save', targetDir))

class FakeHeaders(dict):

    def getheader(self, header):
        return self[header]

class FakeURL(object):

    data = 'this is some data'

    def __init__(self, url=None):
        self.url = url
        self.headers = FakeHeaders()

        header = 'attachment; filename="%s"' % url.rsplit('/')[-1]
        self.headers['Content-Disposition'] = header

    def geturl(self):
        return self.url

    def read(self):
        return self.data

class TemporaryFileTests(object):

    def setup_method(self, method):
        self.tempfiles = set()
        self.tempdirs = set()

    def teardown_method(self, method):
        for filename in self.tempfiles:
            os.remove(filename)

        for dirname in self.tempdirs:
            shutil.rmtree(dirname)

    def tempdir(self):
        path = tempfile.mkdtemp()
        self.tempdirs.add(path)
        return path

    def tempfile(self):
        h, path = tempfile.mkstemp()
        self.tempfiles.add(path)
        os.close(h)
        return path

class TestsWithInstallDirAndZipFile(TemporaryFileTests):

    def setup_method(self, method):
        super(TestsWithInstallDirAndZipFile, self).setup_method(method)
        self.zipfile = os.path.join(os.path.dirname(__file__), 'SomeAddon.zip')
        self.data = file(self.zipfile, 'rb').read()

        self.installdir = tempfile.mkdtemp()

    def teardown_method(self, method):
        super(TestsWithInstallDirAndZipFile, self).teardown_method(method)
        shutil.rmtree(self.installdir)

    def path(self, *path):
        return os.path.join(self.installdir, *path)
